<template>
  <div class="interview-chat-container">
    <!-- 头部信息 -->
    <div class="chat-header">
      <div class="header-left">
        <el-button @click="goBack" size="small" circle>
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
        <div class="interview-info">
          <h3>{{ jobTitle }}</h3>
          <p>{{ companyName }} - AI面试练习</p>
        </div>
      </div>
      <div class="header-right">
        <el-button @click="endInterview" type="danger" size="small">
          结束面试
        </el-button>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-content" ref="chatContentRef">
      <div class="messages-container">
        <div
          v-for="message in messages"
          :key="message.id"
          class="message-item"
          :class="{ 'user-message': message.role === 'user', 'ai-message': message.role === 'assistant' }"
        >
          <div class="message-avatar">
            <el-icon v-if="message.role === 'user'"><User /></el-icon>
            <el-icon v-else><Cpu /></el-icon>
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
        
        <!-- 正在输入指示器 -->
        <div v-if="isAiTyping" class="message-item ai-message typing">
          <div class="message-avatar">
            <el-icon><Cpu /></el-icon>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <div class="input-container">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入您的回答..."
          :disabled="isLoading"
          @keydown.ctrl.enter="sendMessage"
          resize="none"
        />
        <div class="input-actions">
          <div class="input-tips">
            <span>Ctrl + Enter 发送</span>
          </div>
          <el-button
            type="primary"
            @click="sendMessage"
            :loading="isLoading"
            :disabled="!inputMessage.trim()"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 结束面试确认对话框 -->
    <el-dialog
      v-model="showEndDialog"
      title="结束面试"
      width="400px"
      :close-on-click-modal="false"
    >
      <p>确定要结束本次面试练习吗？面试记录将会被保存。</p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEndDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmEndInterview">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, User, Cpu } from '@element-plus/icons-vue'
import { interviewPracticeApi } from '@/api/interview'
import { useUserStore } from '@/stores/user'
import { sendStreamingRequest, parseDifyStreamMessage } from '@/utils/streamingApi'

// 路由和参数
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const jobId = ref(route.params.jobId)
const jobTitle = ref(route.query.jobTitle || '未知岗位')
const companyName = ref(route.query.companyName || '未知公司')

// 响应式数据
const chatContentRef = ref(null)
const inputMessage = ref('')
const isLoading = ref(false)
const isAiTyping = ref(false)
const showEndDialog = ref(false)
const conversationId = ref(null)
const sessionId = ref(null)
const currentStreamingMessage = ref(null)

// 消息列表
const messages = ref([])

// 初始化
onMounted(() => {
  initializeChat()
})

// 页面卸载前保存会话
onBeforeUnmount(() => {
  saveConversation()
})

// 初始化聊天
const initializeChat = async () => {
  try {
    // 创建练习会话
    const sessionData = {
      job_id: jobId.value,
      job_title: jobTitle.value,
      company_name: companyName.value
    }

    const response = await interviewPracticeApi.createPracticeSession(sessionData)
    sessionId.value = response.data.id
    conversationId.value = response.data.conversation_id

    // 添加欢迎消息
    const welcomeMessage = {
      id: Date.now(),
      role: 'assistant',
      content: '您好！我是鸥鹏面试管练习助手，准备好之后请输入 "开始练习" 开始本次练习吧！',
      timestamp: new Date()
    }
    messages.value.push(welcomeMessage)
    scrollToBottom()
  } catch (error) {
    console.error('初始化聊天失败:', error)
    ElMessage.error('初始化聊天失败，请刷新页面重试')
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value || !sessionId.value) return

  const userMessage = {
    id: Date.now(),
    role: 'user',
    content: inputMessage.value.trim(),
    timestamp: new Date()
  }

  messages.value.push(userMessage)
  const messageContent = inputMessage.value.trim()
  inputMessage.value = ''

  scrollToBottom()

  // 显示AI正在输入
  isAiTyping.value = true
  isLoading.value = true

  try {
    await sendToDify(messageContent)
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')

    // 添加错误消息
    const errorMessage = {
      id: Date.now(),
      role: 'assistant',
      content: '抱歉，我遇到了一些问题，请稍后重试。',
      timestamp: new Date()
    }
    messages.value.push(errorMessage)
    isAiTyping.value = false
    isLoading.value = false
    scrollToBottom()
  }
}

// 发送到Dify工作流
const sendToDify = async (message) => {
  const requestData = {
    query: message,
    response_mode: 'streaming',
    user: userStore.user?.username || 'anonymous',
    conversation_id: conversationId.value,
    inputs: {
      job_title: jobTitle.value,
      company_name: companyName.value,
      job_id: jobId.value
    }
  }

  // 创建流式消息处理
  currentStreamingMessage.value = {
    id: Date.now(),
    role: 'assistant',
    content: '',
    timestamp: new Date()
  }

  messages.value.push(currentStreamingMessage.value)

  try {
    const token = userStore.token
    const headers = token ? { 'Authorization': `Bearer ${token}` } : {}

    await sendStreamingRequest(
      `/api/interviews/practice/sessions/${sessionId.value}/messages/`,
      requestData,
      {
        onStart: () => {
          console.log('开始接收流式消息')
        },
        onMessage: (streamMessage) => {
          const parsed = parseDifyStreamMessage(streamMessage)

          switch (parsed.type) {
            case 'message':
              // 更新当前消息内容
              if (currentStreamingMessage.value) {
                currentStreamingMessage.value.content += parsed.content
                scrollToBottom()
              }
              break

            case 'message_end':
              // 消息结束，更新会话ID
              if (parsed.conversationId) {
                conversationId.value = parsed.conversationId
              }
              break

            case 'error':
              console.error('Dify流式消息错误:', parsed.error)
              ElMessage.error('AI回复出现错误')
              break
          }
        },
        onComplete: () => {
          isAiTyping.value = false
          isLoading.value = false
          currentStreamingMessage.value = null
          scrollToBottom()
        },
        onError: (error) => {
          console.error('流式请求错误:', error)
          isAiTyping.value = false
          isLoading.value = false
          currentStreamingMessage.value = null

          // 移除失败的消息并添加错误提示
          if (messages.value.length > 0 && messages.value[messages.value.length - 1].content === '') {
            messages.value.pop()
          }

          const errorMessage = {
            id: Date.now(),
            role: 'assistant',
            content: '抱歉，我遇到了一些问题，请稍后重试。',
            timestamp: new Date()
          }
          messages.value.push(errorMessage)
          scrollToBottom()
        }
      },
      headers
    )
  } catch (error) {
    throw error
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContentRef.value) {
      chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
    }
  })
}

// 格式化消息内容
const formatMessage = (content) => {
  return content.replace(/\n/g, '<br>')
}

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 返回上一页
const goBack = () => {
  if (messages.value.length > 1) {
    ElMessageBox.confirm(
      '确定要离开吗？当前对话将会被保存。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      saveConversation()
      router.back()
    })
  } else {
    router.back()
  }
}

// 结束面试
const endInterview = () => {
  showEndDialog.value = true
}

// 确认结束面试
const confirmEndInterview = () => {
  saveConversation()
  showEndDialog.value = false
  router.push({ name: 'InterviewPractice' })
}

// 保存会话记录
const saveConversation = async () => {
  if (!sessionId.value) return

  try {
    await interviewPracticeApi.endPracticeSession(sessionId.value)
    console.log('会话记录已保存')
  } catch (error) {
    console.error('保存会话记录失败:', error)
  }
}
</script>

<style scoped>
.interview-chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.interview-info h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.interview-info p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.messages-container {
  max-width: 800px;
  margin: 0 auto;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
  gap: 12px;
}

.message-item.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}

.user-message .message-avatar {
  background: var(--el-color-primary);
  color: white;
}

.ai-message .message-avatar {
  background: var(--el-color-info-light-8);
  color: var(--el-color-info);
}

.message-content {
  max-width: 70%;
  min-width: 100px;
}

.user-message .message-content {
  text-align: right;
}

.message-text {
  background: var(--el-bg-color);
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.6;
  word-wrap: break-word;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.user-message .message-text {
  background: var(--el-color-primary);
  color: white;
}

.message-time {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  margin-top: 4px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
  background: var(--el-bg-color);
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--el-color-info);
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input {
  background: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color);
  padding: 16px 24px;
}

.input-container {
  max-width: 800px;
  margin: 0 auto;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.input-tips {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.dialog-footer {
  text-align: center;
}
</style>
